-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local singleton = require 'mc.singleton'
local log = require 'mc.logging'
local vrd_chip_object = require 'vrd.chip.vrd_chip_obj'
local ind_vrd_service = require 'independent_vrd.ind_vrd_service'
local mcu_service = require 'mcu.mcu_service'
local cmn = require 'common'

local sub_component_service = {}
sub_component_service.__index = sub_component_service
function sub_component_service:on_add_object(class_name, object, position)
    local switch = {
        ['VrdChip'] = function ()
            local vrd_info = mcu_service.get_instance():get_vrd_info()
            local obj = vrd_chip_object.new(object, position)
            obj:update_vrd_info(vrd_info)
            table.insert(self.vrd_chips, obj)
        end
    }
    if switch[class_name] then
        log:notice('[VrdChip] Add object, class: %s, position: %s', class_name, position)
        switch[class_name]()
    end
end


function sub_component_service:on_delete_object(class_name, object, position)
    local switch = {
        ['VrdChip'] = function ()
            cmn.remove_ele_by_position(self.vrd_chips, position)
        end
    }
    if switch[class_name] then
        log:notice('[VrdChip] Delete object, class: %s, position: %s', class_name, position)
        switch[class_name]()
    end
end

function sub_component_service.new()
    return setmetatable({}, sub_component_service)
end

local function update_vrd_info(self, vrd_info)
    log:notice('[VrdChip] listen vrd_info changed')
    for _, v in pairs(self.vrd_chips) do
        v:update_vrd_info(vrd_info)
    end
end

function sub_component_service:init()
    self.vrd_chips = {}
    self.vrd_info = {}
    mcu_service.get_instance().vrd_info_changed:on(function (vrd_info)
        update_vrd_info(self, vrd_info)
    end)
    ind_vrd_service.get_instance().vrd_info_changed:on(function (vrd_info)
        update_vrd_info(self, vrd_info)
    end)
    log:info('[sub_component_service] init finished.')
end

return singleton(sub_component_service)